package com.herench.bunch.clinic.convert;

import ca.uhn.hl7v2.model.GenericComposite;
import ca.uhn.hl7v2.model.GenericPrimitive;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Varies;
import ca.uhn.hl7v2.model.v24.datatype.CE;
import ca.uhn.hl7v2.model.v24.group.RTB_K13_ROW_DEFINITION;
import ca.uhn.hl7v2.model.v24.message.QBP_Q11;
import ca.uhn.hl7v2.model.v24.message.QRY_Q01;
import ca.uhn.hl7v2.model.v24.message.RTB_K13;
import ca.uhn.hl7v2.model.v24.segment.MSA;
import ca.uhn.hl7v2.model.v24.segment.MSH;
import ca.uhn.hl7v2.model.v24.segment.RDT;
import ca.uhn.hl7v2.parser.DefaultModelClassFactory;
import com.herench.bunch.clinic.handler.ProxyMsgCodeConstant;
import com.herench.bunch.clinic.support.ProxyMsgTemplate;
import com.herench.bunch.commons.support.RequestMessage;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Iterator;

public class AppointConvert extends AbstractMessageConvert {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public Document doToMessage(RequestMessage requestMessage) throws Exception {
        Document document = ProxyMsgTemplate.getInMsgAppoint(ProxyMsgCodeConstant.APPOINT);
        Element dataRow = document.getRootElement().element("CommitData").addElement("DataNode1").addElement("DataRow");
        QBP_Q11 hl7 = (QBP_Q11) requestMessage.getHl7Message();
        GenericComposite gc = (GenericComposite) hl7.getQPD().getQpd3_UserParametersInsuccessivefields().getData();
        if (gc != null) {
            Varies varies = (Varies) gc.getComponent(1);
            if (varies != null) {
                GenericPrimitive primitive = (GenericPrimitive) varies.getData();
                String qpdString = primitive.getValue();
                String[] qpds = qpdString.split("#");
                if (qpds.length < 2) {
                    throw new RuntimeException("缺少必要参数");
                }
                for (String qpd : qpds) {
                    String[] temp = qpd.split("=");
                    if(temp.length>1){
                        dataRow.addAttribute(temp[0], temp[1] != null ? temp[1] : "");
                    }else {
                        dataRow.addAttribute(temp[0], "");
                    }
                }
            }
        }
        String res = document.asXML();
        logger.info(requestMessage.getMsgCode() + " to HIS XML = "+ res);
        return document;
    }

    @Override
    public Message doFromMessage(String message) throws Exception {
        Assert.notNull(message, "message 为空");
        logger.info("200040 from HIS XML = "+ message);

        Document doc = ProxyMsgTemplate.getOutMsgTpl(message);
        RTB_K13 rtbK13 = new RTB_K13();
        rtbK13.initQuickstart("RTB_K13", "RTB_K13", "P");
        MSH msh = rtbK13.getMSH();
        initResponseMessageMSH(msh);

        MSA msa = rtbK13.getMSA();
        String res = doc.getRootElement().element("Result").element("Info").attributeValue("EXECUTE_FLAG");
        if ("0".equals(res)){
            res = "1";
        }
        msa.getErrorCondition().getCe1_Identifier().setValue(res);
        msa.getErrorCondition().getCe2_Text().setValue(doc.getRootElement().element("Result").element("Info").attributeValue("EXECUTE_MESSAGE"));

        if("1".equals(res)) {
            RTB_K13_ROW_DEFINITION definition = rtbK13.getROW_DEFINITION();
            Element DataNode1 = doc.getRootElement().element("ReturnData").element("DataNode1");

            int index = 0;
            for (Iterator<Element> iterator = DataNode1.elementIterator(); iterator.hasNext(); ) {
                Element el = iterator.next();
                RDT rdt = new RDT(rtbK13, new DefaultModelClassFactory());
                CE ce = new CE(rtbK13);
                ce.getCe1_Identifier().setValue("RD");
                StringBuffer buffer = new StringBuffer();
                buffer.append("ClinicVisitDate=").append(el.attributeValue("CLINIC_VISIT_DATE")).append("#")
                        .append("ClinicLabel=").append(el.attributeValue("CLINIC_LABEL")).append("#")
                        .append("TimeDesc=").append(el.attributeValue("TIME_DESC")).append("#")
                        .append("HourStart=").append(el.attributeValue("HOUR_START")).append("#")
                        .append("HourEnd=").append(el.attributeValue("HOUR_END")).append("#")
                        .append("RegistOrder=").append(el.attributeValue("REGIST_ORDER")).append("#")
                        .append("ApptedId=").append(el.attributeValue("APPTED_ID")).append("#")
                        .append("PatientName=").append(el.attributeValue("PATIENT_NAME")).append("#")
                        .append("Sex=").append(el.attributeValue("SEX")).append("#")
                        .append("ChargeType=").append(el.attributeValue("CHARGE_TYPE")).append("#")
                        .append("DateOfBirth=").append(el.attributeValue("DATE_OF_BIRTH")).append("#")
                        .append("InsuranceNo=").append(el.attributeValue("INSURANCE_NO")).append("#")
                        .append("IdNo=").append(el.attributeValue("ID_NO")).append("#")
                        .append("phoneNumber=").append(el.attributeValue("PHONE_NUMBER")).append("#")
                        .append("CredentialsNo=").append(el.attributeValue("CREDENTIALS_NO")).append("#")
                        .append("CredentialsType=").append(el.attributeValue("CREDENTIALS_TYPE")).append("#")
                        .append("AppointDate=").append(el.attributeValue("APPOINT_DATE")).append("#")
                        .append("AppointScheduleTime=").append(el.attributeValue("APPOINT_SCHEDULE_TIME")).append("#")
                        .append("ReportStartTime=").append(el.attributeValue("REPORT_START_TIME")).append("#")
                        .append("ReportEndTime=").append(el.attributeValue("REPORT_END_TIME")).append("#")
                        .append("Guidelines=").append(el.attributeValue("GUIDELINES")).append("#")
                        .append("AppointSurplus=").append(el.attributeValue("APPOINT_SURPLUS")).append("#")
                        .append("ClinicType=").append(el.attributeValue("CLINIC_TYPE")).append("#")
                        .append("MessageResult=").append(el.attributeValue("MESSAGE_RESULT"));
                ce.getCe2_Text().setValue(buffer.toString());
                rdt.getColumnValue().setData(ce);
                definition.insertRDT(rdt, index++);
            }
        }
        return rtbK13;
    }



    @Override
    public Message generatorReqMessage() throws Exception {
        QRY_Q01 qryQ01 = new QRY_Q01();
        qryQ01.initQuickstart("QRY_Q01", "QRY_Q01", "A");
        
        return null;
    }
}
